// pages/publish/index.js
import {apiUrl} from '../../config';

const app = getApp();
let token = null;

Page({
  data: {
    content: '',
    isReply: false,
    thread_id: 0,
    receiver_id: 0,
    index: 0
  },
  onLoad(options) {
    this.setData({
      thread_id: options.thread_id || 0,
      isReply: options.receiver_id || false,
      receiver_id: options.receiver_id || 0,
      index: Number(options.index) || 0
    });
    token = app.globalData.token;
  },
  setComment(e) {
    this.setData({content: e.detail.value});
  },
  postComment() {
    const {thread_id, content, receiver_id, index} = this.data;
    if (!!!content.length) {
      return ;
    }
    wx.showLoading({
      title: '发布中...',
    });
    wx.request({
      url: apiUrl + '/post-comment', //仅为示例，并非真实的接口地址
      method: 'POST',
      header: {
        Authorization: token
      },
      data: {
        thread_id,
        content,
        receiver_id,
        type: 0
      },
      success: (res) => {
        console.log(res);
        wx.hideLoading()
        switch (Number(res.data.code)) {
          case 1:
            {
              if (index > -1) {
                app.globalData.feeds[index].reply_list.unshift({
                  author: {
                    nickname: app.globalData.userInfo.nickname
                  },
                  content: '测试测试'
                });
              }
              wx.showToast({
                title: '发表成功',
                icon: 'success',
                duration: 1000
              });
              setTimeout(() => {
                wx.navigateBack();
              }, 1000);
              break;
            }
          default:
            {
              wx.showModal({
                content: '发表失败',
                confirmText: '知道了',
                showCancel: false
              });
              break;
            }
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showModal({
          content: '发表失败',
          confirmText: '知道了',
          showCancel: false
        });
      }
    });
  }
})
